package src

import (
//	"fmt"
	"net/http"
	"html/template"
	"appengine"
	"appengine/urlfetch"
	"utils"
	"io/ioutil"
	"github.com/russross/blackfriday"
	"appengine/memcache"
	"time"
)

func init() {
	http.HandleFunc("/submit", submitHandler)
}

func submitHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	url := r.FormValue("url")
	status := 0
	message := ""
	name := ""
	description := ""
	var content template.HTML
	
	
	if url != "" && utils.CheckUrl(url) {
		c := appengine.NewContext(r)
		client := urlfetch.Client(c)
		resp, err := client.Get(url)
		
		if err != nil {
			panic(err.Error())
		}
		
		contentType := resp.Header["Content-Type"]
		
		defer resp.Body.Close()
    	contents, err := ioutil.ReadAll(resp.Body)
		
		if utils.StringInSlice("text/plain", contentType) {
			status = 1
			
			message = "Get Url " + url + " success"
			content = template.HTML(blackfriday.MarkdownCommon(contents))
			description = utils.GetStringSpecial(string(contents))
			
			if description == "" {
				description = utils.GetStringUpperLongest(string(contents))
			}
			
			name = utils.GetAlias(description)
			
			var readme utils.Readme
			readme.Id = 1000
			readme.Name = name
			readme.Content = string(contents)
			readme.Description = description
			readme.Url = url
			readme.Created = time.Now()
			
			utils.InsertReadme(readme, r)
		} else {
			message = "Your url is not readme format. Please check again."
		}
			
	} else if url != "" && !utils.CheckUrl(url) {
		message = "Your url is not valid. Please check again."
	}
	
	var recent = [] utils.Readme {}
  	memcache.Gob.Get(c, "recent", &recent)
	
	t := template.Must(template.New("Submit").ParseFiles("templates/pages/submit.html", "templates/layouts/header.html", "templates/layouts/footer.html"))
	
	t.Execute(w, map[string]interface{}{"status": status, "message" : message, "content" : content, "description" : description, "name" : name, "url" : url, "recent" : recent})
	
}

